package cn.bdqn.controller;

import cn.bdqn.common.Config;
import cn.bdqn.model.SysRoles;
import cn.bdqn.model.SysUsers;
import cn.bdqn.result.Result;
import cn.bdqn.result.ResultUtils;
import cn.bdqn.service.SysRolesService;
import cn.bdqn.service.SysUsersService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;

/**
 * 用户表(SysUsers)表控制层
 *
 * @author makejava
 * @since 2021-03-19 22:55:14
 */
@Controller
public class SysUsersController {

    /**
     * 服务对象
     */
    @Resource
    private SysUsersService sysUsersService;

    @Autowired
    private SysRolesService sysRolesService;

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("selectOne")
    public SysUsers selectOne(Long id) {
        return this.sysUsersService.queryById(id);
    }


    /**
     * @Author: hah
     * @Date: 2021-03-25 10:03:53
     * @Description: 加载头像
     * @param userId
     * @return void
     **/
    @RequestMapping("/api/sysUsers/showImg")
    public void showImg(@RequestParam("userId")Long userId, HttpServletRequest request, HttpServletResponse response)throws IOException {

        //获取当前文件路径
        System.out.println(request.getSession().getServletContext().getRealPath("/statics/images/img1.jpg"));

        //通过id查询用户数据 ,获取头像地址
        SysUsers users = sysUsersService.queryById(userId);
        String headUrl = users.getHeadUrl();
        //获取路径 if(headUrl为空) Config.SESSION_IMAGER_DEFAULT = users.getHeadUrl()
        String path =(StringUtils.isEmpty(headUrl) ? Config.SESSION_IMAGER_DEFAULT :users.getHeadUrl());

        //文件输入流
        FileInputStream fileInputStream = new FileInputStream(path);
        byte[] bytes = new byte[fileInputStream.available()];
        fileInputStream.read(bytes);//写入
        response.setContentType("image/*");

        OutputStream outputStream = response.getOutputStream();
        outputStream.write(bytes);
        outputStream.flush();
        outputStream.close();
        fileInputStream.close();
    }


    @RequestMapping("/api/users/list")
    public String getUserList(@RequestParam(value = "pageNo",required = false,defaultValue = "1")Integer pageNum,
                              Model model){
        //pageNum，pageSize设置每页显示条数
        PageHelper.startPage(pageNum,4);
        List<SysUsers> userList = sysUsersService.getUsersList();
        PageInfo<SysUsers> info = new PageInfo<>(userList, pageNum);
        model.addAttribute("pages",info);
        return "userList";
    }

    /**
     * @Author: hah
     * @Date: 2021-03-25 21:03:38
     * @Description:  进入添加用户页面
     * @return java.lang.String
     **/
    @GetMapping("/api/users/addUser")
    public String toaddUser(Model model){
        List<SysRoles> sysRoles = sysRolesService.getAll();
        model.addAttribute("sysRoles", sysRoles);
        return "userAdd";
    }

    /**
     * @Author: hah
     * @Date: 2021-03-26 15:03:44
     * @Description: 判断账户是否，重复
     * @param account
     * @return java.lang.String
     **/
    @ResponseBody
    @RequestMapping("/api/users/accountExist.json")
    public Result accountExist(@RequestParam("account")String account){
        List<SysUsers> list = sysUsersService.getUsersList();
        for (SysUsers sysUsers: list) {
            //if相等则存在
            if(sysUsers.getAccount().equals(account)) {
                return ResultUtils.defaultFailure(sysUsers);
            }
        }
        return  ResultUtils.returnDataSuccess(list);
    }

    /**
     * @Author: hah
     * @Date: 2021-03-26 16:03:24
     * @Description: 添加用户
     * @param model
     * @param sysUsers
     * @param request
     * @param response
     * @param multipartFile
     * @return java.lang.String
     **/
    @PostMapping("/api/users/addUser")
    public String doaddUser(Model model, SysUsers sysUsers, HttpServletRequest request, HttpServletResponse response
                            , @RequestParam(value = "userImg",required = false)MultipartFile multipartFile){
        // 添加到，新用户的创建人中     //获取Session中的user,id
        sysUsers.setCreatedUserId(((SysUsers) request.getSession().getAttribute("userSession")).getId());

        Result<SysUsers> result = sysUsersService.addUser(sysUsers, multipartFile);

        if (result.getCode().equals("200")) {
            return "redirect:/api/users/list";
        }

        //返回错误信息
        request.setAttribute("fileUploadError",result.msg);
        return "redirect:/api/users/addUser";

    }

}
